import { useState, useMemo, useEffect } from 'react';
import getInvoiceType from '../lib/getInvoiceType';
function useGenActiveInvoice(invoices = [], baseActiveKey, invoicesExtInfo, onChange) {
    const [activeKey, setActiveKey] = useState(() => {
        return invoices?.length > 0 && invoices[0].invoiceDataCode;
    });
    const activedFile = useMemo(() => {
        let relatedInfo = invoicesExtInfo.find(item => { return item.invoiceDataCode === activeKey }) || {};
        let targetInvoice = invoices.find(item => { return item.invoiceDataCode === activeKey }) || {};
        return { ...targetInvoice, loading: relatedInfo.loading, viewUrl: relatedInfo?.viewUrl };
    }, [invoices, invoicesExtInfo, activeKey]);
    const changeActiveFile = (v) => {
        setActiveKey(v);
        typeof onChange === 'function' && onChange(invoices.find(item => { return item.invoiceDataCode === v }) || {});
    }
    /* 当外部的activeKey和组件中不一致时，以外部为准 */
    useEffect(() => {
        if (baseActiveKey && activeKey !== baseActiveKey) setActiveKey(baseActiveKey);
    }, [baseActiveKey]);
    return { activeKey, setActiveKey: changeActiveFile, activedFile, activeFileType: getInvoiceType(activedFile?.attachmentFiles?.[0] || {}) }
}
export default useGenActiveInvoice;